package com.janwen.spring.trx.declarative;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;


@Service("serviceB")
public class ServiceBImpl implements ServiceB {

	@Autowired
	private FooService fooService;
	@Autowired
	private ServiceA serviceA;
	@Autowired
	private DataSource dataSource;
	
	@Override
	public Foo getFoo(String fooName) {
		String sql = "SELECT * FROM stuff WHERE name=?";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		List<Map<String,Object>> fooList = jdbcTemplate.queryForList(sql,fooName);
		if(fooList != null){
			Map<String,Object> fooMap = fooList.get(0);
			Foo foo = new Foo();
			foo.setAge((Integer)fooMap.get("age"));
			foo.setName(fooMap.get("name").toString());
			return foo;
		}
		return null;
	}

	@Override
	public void updateFoo(Foo foo) {
		try {
			JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
			String sql  = "update stuff SET name=?,age=?";
			jdbcTemplate.update(sql,foo.getName(),foo.getAge()+2);
			Integer.parseInt("2a");
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void insertFoo(Foo foo) {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		String sql  = "INSERT INTO stuff SET name=?,age=?";
		jdbcTemplate.update(sql,foo.getName(),foo.getAge());
		//ServiceA内部调用DefaultFooService,DefaultFooService throws runtimeException,整个事务正常回滚
		serviceA.getFoo(foo.getName());
	}

	@Override
	public void cleraData() {
		fooService.clear();
	}
     /**
      * readonly 开始的事务,在get*方法内部调用非get*方法进行write操作,clear事务不会成功
      */
	@Override
	public void getCleraData() {
		fooService.clear();
		
	}

}
